<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="站点名称" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入站点名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="busPlateNumber">
        <el-input
          v-model="queryParams.busPlateNumber"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="播放状态" prop="playStatus">
        <el-select v-model="queryParams.playStatus" placeholder="请选择播放状态" clearable>
          <el-option label="成功" value="成功"></el-option>
          <el-option label="失败" value="失败"></el-option>
          <el-option label="手动触发" value="手动触发"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="触发方式" prop="isManualTrigger">
        <el-select v-model="queryParams.isManualTrigger" placeholder="请选择触发方式" clearable>
          <el-option label="自动" :value="0"></el-option>
          <el-option label="手动" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="播放时间" prop="playTime">
        <el-date-picker clearable
          v-model="queryParams.playTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateRangeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bus:logs:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-pie-chart"
          size="mini"
          @click="showStatistics"
        >统计分析</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="logsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="播放时间" align="center" prop="playTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.playTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点名称" align="center" prop="stationName" width="120" />
      <el-table-column label="车牌号" align="center" prop="busPlateNumber" width="100" />
      <el-table-column label="线路" align="center" prop="routeName" width="80" />
      <el-table-column label="报站类型" align="center" prop="announcementTypeName" width="100" />
      <el-table-column label="播放状态" align="center" prop="playStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.playStatus)">
            {{ scope.row.playStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="触发方式" align="center" prop="isManualTrigger" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isManualTrigger === 1 ? 'warning' : 'info'">
            {{ scope.row.isManualTrigger === 1 ? '手动' : '自动' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="GPS位置" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.gpsLatitude && scope.row.gpsLongitude">
            <el-button type="text" size="mini" @click="showLocation(scope.row)" icon="el-icon-location">
              查看位置
            </el-button>
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="司机工号" align="center" prop="driverId" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="playVoice(scope.row)"
            v-if="scope.row.voiceFilePath"
          >播放</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <div v-if="form.id">
        <h4 style="margin-bottom: 20px; color: #409EFF;">
          {{ form.stationName }} - {{ form.announcementTypeName }}
          <el-tag :type="getStatusTagType(form.playStatus)" style="margin-left: 10px;">
            {{ form.playStatus }}
          </el-tag>
        </h4>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="播放时间">
            {{ parseTime(form.playTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ parseTime(form.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </el-descriptions-item>
          <el-descriptions-item label="站点名称">{{ form.stationName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="车牌号">{{ form.busPlateNumber || '-' }}</el-descriptions-item>
          <el-descriptions-item label="线路">{{ form.routeName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="司机工号">{{ form.driverId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="报站类型">{{ form.announcementTypeName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="播放状态">
            <el-tag :type="getStatusTagType(form.playStatus)">
              {{ form.playStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="触发方式">
            <el-tag :type="form.isManualTrigger === 1 ? 'warning' : 'info'">
              {{ form.isManualTrigger === 1 ? '手动触发' : '自动触发' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="GPS精度">
            {{ form.gpsAccuracy ? form.gpsAccuracy + 'm' : '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- GPS位置信息 -->
        <div v-if="form.gpsLatitude && form.gpsLongitude" style="margin-top: 20px;">
          <el-divider content-position="left">GPS位置信息</el-divider>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="纬度">{{ form.gpsLatitude }}</el-descriptions-item>
            <el-descriptions-item label="经度">{{ form.gpsLongitude }}</el-descriptions-item>
            <el-descriptions-item label="精度">{{ form.gpsAccuracy }}m</el-descriptions-item>
          </el-descriptions>
          <div style="text-align: center; margin-top: 10px;">
            <el-button type="primary" @click="openMap" icon="el-icon-location">在地图上查看</el-button>
          </div>
        </div>

        <!-- 错误信息 -->
        <div v-if="form.errorMessage" style="margin-top: 20px;">
          <el-divider content-position="left">错误信息</el-divider>
          <el-alert
            :title="form.errorMessage"
            type="error"
            :closable="false">
          </el-alert>
        </div>

        <!-- 语音播放 -->
        <div v-if="form.voiceFilePath && form.playStatus === '成功'" style="margin-top: 20px;">
          <el-divider content-position="left">语音播放</el-divider>
          <div style="text-align: center; margin-bottom: 10px;">
            <el-button type="primary" icon="el-icon-video-play" @click="playVoice(form)">
              播放报站语音
            </el-button>
          </div>
          <audio :src="getVoiceUrl(form.voiceFilePath)" controls style="width: 100%;">
            您的浏览器不支持音频播放
          </audio>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 位置显示对话框 -->
    <el-dialog title="GPS位置" :visible.sync="locationDialogVisible" width="600px" append-to-body>
      <div style="text-align: center;">
        <p>纬度: {{ currentLocation.latitude }}</p>
        <p>经度: {{ currentLocation.longitude }}</p>
        <p>精度: {{ currentLocation.accuracy }}m</p>
        <el-button type="primary" @click="openMap" icon="el-icon-location">在地图上查看</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAnnouncementLogs, getAnnouncementLogs, delAnnouncementLogs, exportAnnouncementLogs } from "@/api/bus/announcementLogs"

export default {
  name: "AnnouncementLogs",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报站记录日志表格数据
      logsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 位置对话框可见性
      locationDialogVisible: false,
      // 当前位置信息
      currentLocation: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationName: null,
        busPlateNumber: null,
        playStatus: null,
        isManualTrigger: null,
        playTime: null,
        playTimeStart: null,
        playTimeEnd: null
      },
      // 表单参数
      form: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询报站记录日志列表 */
    getList() {
      this.loading = true
      listAnnouncementLogs(this.queryParams).then(response => {
        this.logsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 取消按钮 */
    cancel() {
      this.open = false
      this.locationDialogVisible = false
      this.reset()
    },

    /** 表单重置 */
    reset() {
      this.form = {}
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.playTimeStart = null
      this.queryParams.playTimeEnd = null
      this.handleQuery()
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 查看详情 */
    handleView(row) {
      this.reset()
      const id = row.id
      getAnnouncementLogs(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "报站日志详情"
      })
    },

    /** 播放语音 */
    playVoice(row) {
      if (!row.voiceFilePath) {
        this.$message.error('语音文件不存在')
        return
      }

      this.$message.info(`正在播放：${row.stationName} - ${row.announcementTypeName}`)

      const audio = new Audio(this.getVoiceUrl(row.voiceFilePath))
      audio.play().catch(error => {
        console.error('音频播放失败:', error)
        this.$message.error('音频播放失败: ' + (error.message || '网络错误'))
      })
    },

    /** 显示位置 */
    showLocation(row) {
      this.currentLocation = {
        latitude: row.gpsLatitude,
        longitude: row.gpsLongitude,
        accuracy: row.gpsAccuracy
      }
      this.locationDialogVisible = true
    },

    /** 在地图上查看 */
    openMap() {
      const lat = this.currentLocation.latitude || this.form.gpsLatitude
      const lng = this.currentLocation.longitude || this.form.gpsLongitude

      // 使用高德地图
      const url = `https://uri.amap.com/marker?position=${lng},${lat}&name=报站位置&src=smartbus`
      window.open(url, '_blank')
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('bus/announcement-logs/export', {
        ...this.queryParams
      }, `announcement_logs_${new Date().getTime()}.xlsx`)
    },

    /** 统计分析 */
    showStatistics() {
      this.$message.info('统计分析功能开发中...')
    },

    /** 日期范围变化处理 */
    handleDateRangeChange(value) {
      if (value && value.length === 2) {
        this.queryParams.playTimeStart = value[0]
        this.queryParams.playTimeEnd = value[1]
      } else {
        this.queryParams.playTimeStart = null
        this.queryParams.playTimeEnd = null
      }
    },

    /** 获取状态标签类型 */
    getStatusTagType(status) {
      const statusTypes = {
        '成功': 'success',
        '失败': 'danger',
        '手动触发': 'warning'
      }
      return statusTypes[status] || 'info'
    },

    /** 获取语音文件URL */
    getVoiceUrl(filePath) {
      if (!filePath) return ''
      return process.env.VUE_APP_BASE_API + filePath
    }
  }
}
</script>

<style scoped>
.el-descriptions {
  margin-bottom: 20px;
}

.app-container {
  padding: 20px;
}
</style>